import React, { Component } from 'react';
import MyEchart from '@/components/MyEcharts';
import EmptyData from '@/components/EmptyData';
import CardWrapper from '../../card-wrapper';
import getPieOption from '../options/pie';
import getBarOption from '../options/labelBar';
import { Table, Select, Tooltip, Pagination, Loading,Input } from '@knownsec/react-component';
import { Link } from 'react-router-dom';
import {getGroupList,getGroupPercent,getTopData} from '~/API';
import moment from 'moment';
import './index.less';
import RuleTable from '@/components/RuleTable'
import CopyText from '@/components/copy'
import { filterNull } from '@/utils';

const info=localStorage.info?JSON.parse(localStorage.info).modules:[]
const SelectOption = Select.Option;
class Vul extends Component {
  constructor(props) {
    super(props);
    this.state = {
        target_group_name:'',
      dataList: [],
      percentObj: {},
      topXlist: [],
      topYlist: [],
      page: 1,
      limit: 10,
      queryVal:{target_name:'',target_url:''},
      total: 0,
      loading: false,
    }
  }
  isreturn(data,url){
    if(data >= 0){
      return data
    }else{
      return '-'
    }
  }
  getVulSiteList = () => {
    let columns = [
      {
        title: '业务系统',
        dataIndex: 'target_url',
        render: (e, row) => {
          const name = row.target_name ? row.target_name : row.target_title
          return (
            <Tooltip
              overlay={
                <>
                  <p>业务系统：<CopyText text={e}/></p>
                  <p>业务系统名称：{name || '暂未设置'}</p>
                </>
              }
              placement="topLeft"
            >
              <div>
                <Link className="hrefName" to="#" onClick={() => {
                  window.open(e);
                }}>
                  {e}
                </Link>
                <div
                  className="targetName"
                  style={{ color: name ? '#2A2B31' : '#ccc' }}
                  onClick={() => {
                    const random = Math.random();
                    this.changeName(row);
                  }}
                >
                  {name || '点击设置业务系统名称'}
                </div>
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: '严重漏洞',
        dataIndex: 'CRITICAL',
        className: 'widthsm',
        render: (value, data) => this.isreturn(data.vul?.CRITICAL,data.total_url),
      },
      {
        title: '高危漏洞',
        dataIndex: 'HIGH',
        className: 'widthsm',
        render: (value, data) =>  this.isreturn(data.vul?.HIGH,data.total_url),
      },
      {
        title: '中危漏洞',
        dataIndex: 'MEDIUM',
        className: 'widthsm',
        render: (value, data) =>  this.isreturn(data.vul?.MEDIUM,data.total_url),
      },
      {
        title: '低危漏洞',
        dataIndex: 'LOW',
        className: 'widthsm',
        render: (value, data) =>  this.isreturn(data.vul?.LOW,data.total_url),
      },
      {
        title: '信息',
        dataIndex: 'INFO',
        className: 'widthsm',
        render: (value, data) => this.isreturn(data.vul?.INFO,data.total_url),
      },
      {
        title: '未知',
        dataIndex: 'UNKNOWN',
        className: 'widthsm',
        render: (value, data) => this.isreturn(data.vul?.UNKNOWN,data.total_url),
      },
      {
        title: '最近监测时间',
        dataIndex: 'ended_at',
        render: (value) => {
          const time = value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p>最近监测时间：{time}</p>
                </>
              }
              placement="topLeft"
            >
                <div>
                  {time}
                </div>
            </Tooltip>
          );
        },
      },
      {
        title: '预计下次监测时间',
        dataIndex: 'next_start_at',
        render: (value) => {
          const time = value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p>预计下次监测时间：{time}</p>
                </>
              }
              placement="topLeft"
            >
                <div>
                  {time}
                </div>
            </Tooltip>
          );
        },
      },
      {
        title: '操作',
        dataIndex: 'option',
        className: 'widthsm',
        render: (value, _data) => (
          <>
            <a href={`/#/dashboard?sid=${_data.task_session_id}&id=${_data.target_id}&type=vul`} target='_blank' className='main-color'>
                查看报表
            </a>
          </>
        ),
      },
    ];
    return columns;
  };
  changeName(row) {
    var _this = this
    _this.props.change(row, _this.props.createForm, function(e){
      if(e){ _this.getRiskList() }
    })
  };
  onSearchChange = (page) => {
    var _this = this
    if(page&&page.page){
      _this.setState({
        page: page.page,
        limit: page.limit
      }, function(){
        _this.getRiskList()
      })
    }else{
      _this.setState({
        page: 1,
        limit: 10
      }, function(){
        _this.getRiskList()
      })
    }
  }
  getRiskList(){
    this.setState({loading: true})
    const {target_name,target_url}=this.state.queryVal
    const data=filterNull({ page: this.state.page, limit: this.state.limit,target_name, target_url})
    getGroupList({type: 'vul', id: this.props.id, data}).then(res =>{
      this.setState({loading: false})
      if(res.status === 'success'){    
        this.setState({dataList: res.data.data, total: res.data.total,target_group_name:res.data.target_group_name})
      }
    })
  }
  getTop(){
    this.setState({loading: true})
    getTopData({type: 'vul', id: this.props.id}).then(res =>{
      let x = [], y = []
      if(res.status === 'success'){
         res.data.top.forEach(item => {
            const xurl = item.target_url || '--'
            const xname = item.target_name ? item.target_name : item.target_title || '--';
            let a = {value: xurl+'||%%'+xname || ''} 
            x.push(a)
            y.push(item.count || 0)
         })
      }
      this.setState({ topXlist: x, topYlist: y, loading: false });
    })
  }
  getpercent(){
    this.setState({loading: true})
    getGroupPercent({type: 'vul', id: this.props.id}).then(res =>{
      this.setState({loading: false})
      if(res.status === 'success'){
        let sdata = {}
        res.data.statistics.forEach(item => { 
          sdata[item.name] = item.target_count
        })
        this.setState({ percentObj: sdata });
      }
    })
  }
  componentDidMount(){
    this.getRiskList()
    this.getpercent()
    this.getTop()
  }
  render() {
    let siteVulPie = [
      {
        name: '安全网站',
        value: this.state.percentObj.safe || 0,
        color: ['#27D586', '#11AB4E'],
      },
      {
        name: '低危',
        value: this.state.percentObj.LOW || 0,
        color: ['#FFEE5F', '#FED831'],
      },
      {
        name: '中危',
        value: this.state.percentObj.MEDIUM || 0,
        color: ['#FBB549', '#F67E23'],
      },
      {
        name: '高危',
        value: this.state.percentObj.HIGH || 0,
        color: ['#FF5757', '#FF0000'],
      },
      {
        name: '严重',
        value: this.state.percentObj.CRITICAL || 0,
        color: ['#FF5757', '#FF0000'],
      },
    ];
    let siteVulPieOption = getPieOption(siteVulPie,true);

    let highVulSiteTop10Data = {
      x: this.state.topXlist,
      y: this.state.topYlist,
      color: [['#FF0000', '#FF8A8A']],
      transpose: true,
      limitXLabelLength: 10,
    };
    let highVulSiteTop10Option = getBarOption(highVulSiteTop10Data);
    const updateTime = new Date()
    let vulSiteList = this.getVulSiteList();
    return (
      <div className="tm-vul">
        <div className="filter">
          <label className="targetName">任务组名称：{this.state.target_group_name||'--'}</label>
          <label>更新时间：{moment(updateTime).format('YYYY-MM-DD HH:mm:ss')}</label>
        </div>
        <div className="state">
          <Loading show={this.state.loading} label='' />
          <CardWrapper title="业务系统风险占比" className="site-vul-pie">
            {siteVulPieOption?<MyEchart option={siteVulPieOption}></MyEchart>:<EmptyData size="small" />}
          </CardWrapper>
          <CardWrapper title="高危漏洞最多的业务系统 TOP 5" className="site-vul-top10">
            {this.state.topXlist.length?(<MyEchart option={highVulSiteTop10Option}></MyEchart>):(<EmptyData size="small" />)}
          </CardWrapper>
        </div>
        <CardWrapper title="业务系统漏洞监测列表" className="vul-site-list">
        <div className="searchTool">
          <Input
            pro
            placeholder="搜索业务系统名称"
            value={this.state.queryVal.target_name}
            search
            className={'search-button'}
            onSearch={(e) => {
              this.onSearchChange({ target_name: e.value });
            }}
            clear
            onChange={(value) => {
              this.setState({queryVal:{...this.state.queryVal,target_name:value.value}})
              if (!value.e) {
              this.onSearchChange();
                return;
              }
            }}
          ></Input>
          <Input
            pro
            placeholder="搜索业务系统地址"
            value={this.state.queryVal?.target_url}
            search
            className={'search-button'}
            onSearch={(e) => {
              this.onSearchChange({ target_url: e.value });
            }}
            clear
            onChange={(value) => {
               this.setState({queryVal:{...this.state.queryVal,target_url:value.value}})
              if (!value.e) {
              this.onSearchChange();
                return;
              }
            }}
          ></Input>
          </div>
        {info.includes('vul')? 
        <Table 
          columns={vulSiteList} 
          tableLoading={this.state.loading}
          loadingLabel=""
          data={this.state.dataList}></Table>:
        <RuleTable columns={vulSiteList} data={this.state.dataList}></RuleTable>
        }
        {(info.includes('vul') && this.state.total > 10) && <Pagination
          key={Number(123)}
          className="pagination"
          current={this.state.page}
          showQuickJumper={{ goButton: true }}
          showSizeChanger={true}
          pageSize={this.state.limit}
          pageSizeOptions={['10', '20', '50']}
          total={this.state.total}
          onChange={(page, size) => {
            this.onSearchChange({ page, limit: size });
          }}
        />}
        </CardWrapper>
      </div>
    );
  }
}

export default Vul;
